package chexuan.game.constant.cmd;

import java.util.HashMap;

import chexuan.game.exception.CmdRegisteredException;
import chexuan.game.exception.NotRegisteredCmdException;
import chexuan.game.interfaces.packet.InterfacePacket;

public class CmdPacketMap {

	public static CmdPacketMap instance;
	private final HashMap<Integer, Class<? extends InterfacePacket>> map = new HashMap<Integer, Class<? extends InterfacePacket>>();

	public static synchronized CmdPacketMap getInstance() {
		if (null == instance) {
			instance = new CmdPacketMap();
		}

		return instance;
	}

	private CmdPacketMap() {
	}

	public void registerCmdPacket(int cmd,
			Class<? extends InterfacePacket> packetClass)
			throws CmdRegisteredException {
		if (map.containsKey(cmd)) {
			String messageFormat = " cmd[%#x] has been registered. ";
			throw new CmdRegisteredException(String.format(messageFormat, cmd));
		}

		map.put(cmd, packetClass);
	}

	public void unregisterCmdPacket(int cmd) {
		if (map.containsKey(cmd)) {
			map.remove(cmd);
		}
	}

	public Class<? extends InterfacePacket> getCmdPacketClass(int cmd)
			throws NotRegisteredCmdException {
		if (map.containsKey(cmd)) {
			String messageFormat = " cmd[%#x] is not registered. ";
			throw new NotRegisteredCmdException(String.format(messageFormat,
					cmd));
		}

		return map.get(cmd);
	}

	public void clear() {
		map.clear();
	}
}
